package utils 
{
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextLineMetrics;
	/**
	 * ...
	 * @author SChabanov
	 */
	public final class TextUtils 
	{
		
		public function TextUtils() 
		{
			throw new Error("static class need for text components")
		}
		
		//fit text to textfield by fontSize
		public static function fitText(t:TextField,factor:Number=0.5):void
		{
			var size:Number = Number(t.getTextFormat().size);
			var tformat:TextFormat = t.getTextFormat();
			while (t.textWidth > t.width || t.textHeight > t.height)
			{
				size-= Math.abs(factor);
				tformat.size = size;
				t.setTextFormat(tformat);
			}
		}
		
		public static function getTextMetrics(input:String, format:TextFormat, lineIndex:int = 0):TextLineMetrics
		{
			var t:TextField = new TextField();
			t.defaultTextFormat = format;
			t.htmlText = input;
			return t.getLineMetrics(lineIndex);
		}
		
		//capitalize first char 
		public static function capitalizeFirstChar(input:String):String
		{
			input.toLowerCase();
			var char:String = input.charAt().toUpperCase();
			var output:String = input.replace(input.charAt(), char);
			return output;
		}
		
			
		public static function translit(value:String):String
		{
			var arrRussian:Array = ["А","Б","В","Г","Д","Е","Ё","Ж","З","И","Й","К","Л","М","Н","О","П","Р","С","Т","У","Ф","Х","Ц","Ч","Ш","Щ","Э","Ю","Я","а","б","в","г","д","е","ё","ж","з","и","й","к","л","м","н","о","п","р","с","т","у","ф","х","ц","ч","ш","щ","ь","ы","ъ","э","ю","я"," "];
			var arrTranslate:Array = ["A","B","V","G","D","E","E","Zh","Z","I","I","K","L","M","N","O","P","R","S","T","U","F","H","C","Ch","Sh","Sh'","E","Yu","Ya","a","b","v","g","d","e","e","zh","z","i","i","k","l","m","n","o","p","r","s","t","u","f","h","c","ch","sh","sh'","'","i","'","e","yu","ya","_"];
			var i:int;
			while (i < arrRussian.length)
			{
				value = (value.split(arrRussian[i])).join(arrTranslate[i]);
				i++;
			}
			return value;
		}
		
		public static function numeral(x:int, v1:String, v234:String, v5i:String):String
		{
			var select:Function = function (mod:int, v1:String, v234:String, v5i:String):String
			{
				if (mod == 1)
					return v1;
				else if ((mod >= 2) && (mod <= 4))
					return v234;
				else
					return v5i;
			}
			
			if ((x % 100) < 20)
				return select (x % 100, v1, v234, v5i);
			
			return select (x % 10, v1, v234, v5i);
		};
		
		
		// Remove n characters from the end of the visible text of the HTMLText you've sent.
		public static function truncateHtmlText(textfield:TextField, truncChars:String = "..."):String
		{
			
			var ratio:Number = textfield.textWidth/textfield.width;
			var numCharsToRemove:Number=0;
			
			if (ratio>1) {
				// Ooops! We're over our limit! 
				numCharsToRemove = textfield.length - (Math.floor(textfield.length / ratio) - truncChars.length);
			}
			
			var myHTMLText:String = textfield.htmlText;
			var copyStr:String = myHTMLText;
			var testStr:String;
			var isEscCode:Boolean = false;
			var char:String;
			var numDeleted:Number = 0;
			var escCodePattern:RegExp = /&#?\w{0,6};$/;
			var curIndex:Number;
			var startIndex:Number;
			var endIndex:Number;
			
			// Scan backwards in our string, skipping anything we find that's between any <tags>
			// we find, and remembering to remove &escaped; codes in their entirety if we find any.
			for (curIndex = myHTMLText.length; curIndex >= 0; curIndex--)
			{
				
				startIndex = curIndex;
				endIndex = curIndex + 1;
				
				// test the character at the chosen index. We want to know if it's special in any way.
				char = (myHTMLText.charAt(curIndex));
				
				// and keep track of everything we haven't tested so far:
				testStr = copyStr.slice(0, endIndex);
				
				if ((char == ">"))
				{
					// This is the end of a tag; skip ahead (or backwards, actually) to 
					// the start of the tag. This may cause problems if we're dealing
					// with a url that has javascript in it, but we'll cross that bridge 
					// when we come to it.
					curIndex = testStr.lastIndexOf("<");
					
				}
				else
				{
					// We're not in a tag, and therefore this is a char that can be deleted.
					
					// However, if this is an escaped character such as &amp; or &#8884; we
					// need to make sure we get the whole thing! This isn't the greatest
					// pattern for this test but it's short and simple.
					isEscCode = (testStr.search(escCodePattern) > -1);
					if (isEscCode)
					{
						startIndex = testStr.lastIndexOf("&");
					}
					
					// Remove the char(s) we've found:
					copyStr = copyStr.slice(0, startIndex) + copyStr.slice(endIndex);
					
					// if startIndex changed for any reason, update curIndex to save a few iterations:
					curIndex = startIndex;
					
					// finally check to see if we've removed the required number of text chars:
					numDeleted++;
					if (numDeleted > numCharsToRemove)
					{
						break;
					}
				}
			}
			// finally, insert an ellipsis at the curIndex:
			
			copyStr = copyStr.slice(0, curIndex) + truncChars + copyStr.slice(curIndex);
			return copyStr;
		}
		/**
		 * simple text truncate like in Flex Label
		 * 
		 * @param	textfield
		 * @param	original
		 * @param	altText
		 */
		public static function truncateTextfield(textfield:TextField, original:String,isHtml:Boolean=false, altText:String = "\u2026"):void
		{
			if (original.length == 0) return
			var rightNeed:int = 4;
			var str:String = original;//.replace(/\s/g, '');
			if (!isHtml) {
				textfield.text = str;
			}
			while (str.length > 1 && textfield.textWidth > (textfield.width-rightNeed))
			{				
				str = str.slice(0, -1);
				if (!isHtml) {
					textfield.text = str + altText;
				}else {
					textfield.htmlText = str + altText;
				}
			}
		
			//trace(“new end->>”,getTimer())
		}
		
		
	}

}